package com.example.yogurtsystem.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yogurtsystem.entity.User;
import com.example.yogurtsystem.entity.excel.UserData;
import com.example.yogurtsystem.exception.ServiceException;
import com.example.yogurtsystem.service.UserService;

/**
 * @author Da
 * @date 2021/08/24
 **/
public class UserExcelListener extends AnalysisEventListener<UserData> {


    private UserService userService;



    public UserExcelListener() {

    }

    public UserExcelListener(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void invoke(UserData userData, AnalysisContext analysisContext) {
        if (userData==null){
            throw new ServiceException("导入数据为空！");
        }

        User exitUser=this.exitUser(userData.getUserId(),userData.getName());
        if (exitUser==null){
            User user = new User();
            user.setId(userData.getUserId());
            user.setName(userData.getName());
            userService.save(user);
        }
    }

    private User exitUser(String userId, String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        User user = userService.getOne(queryWrapper);
        return user;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
